package com.jianggujin.redis.panel;

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Component;
import java.text.MessageFormat;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.JLabel;
import javax.swing.JPanel;

import com.jianggujin.redis.node.RedisKey;
import com.jianggujin.redis.panel.value.ListValuePanel;
import com.jianggujin.redis.panel.value.NoneValuePanel;
import com.jianggujin.redis.panel.value.SetValuePanel;
import com.jianggujin.redis.panel.value.StringValuePanel;
import com.jianggujin.redis.panel.value.UnknownValuePanel;
import com.jianggujin.redis.panel.value.ZSetValuePanel;
import com.jianggujin.redis.panel.value.HashValuePanel;

import lombok.AllArgsConstructor;
import lombok.Getter;

public class KeyValuePanel extends JPanel {
    private CardLayout layout = null;
    private JLabel keyLabel;
    private JLabel ttlLabel;

    private JPanel cardPanel;

    public KeyValuePanel() {
        super(new BorderLayout());

        Box north = Box.createHorizontalBox();
        north.setBorder(BorderFactory.createTitledBorder("Key"));
        keyLabel = new JLabel();
        north.add(keyLabel);
        north.add(Box.createHorizontalGlue());
        ttlLabel = new JLabel();
        north.add(ttlLabel);
        add(north, BorderLayout.NORTH);

        layout = new CardLayout();
        cardPanel = new JPanel(layout);
        cardPanel.setBorder(BorderFactory.createTitledBorder("Value"));

        for (ValueType valueType : ValueType.values()) {
            cardPanel.add(valueType.name(), (Component) valueType.getValuePanel());
        }
        add(cardPanel);
    }

    public void showNone() {
        layout.show(cardPanel, ValueType.none.name());
        this.keyLabel.setText("");
        this.ttlLabel.setText("");
    }

    public void showValue(RedisKey redisKey) {
        this.keyLabel.setText(redisKey.getKey());
        this.ttlLabel.setText(MessageFormat.format("ttl:{0}s", redisKey.getClient().ttl(redisKey.getKey())));
        String type = redisKey.getClient().type(redisKey.getKey());
        ValueType valueType = ValueType.parseOf(type);
        valueType.getValuePanel().showValue(redisKey);
        layout.show(cardPanel, valueType.name());
    }

    @AllArgsConstructor
    @Getter
    private static enum ValueType {
        none(new NoneValuePanel()), string(new StringValuePanel()), list(new ListValuePanel()),
        set(new SetValuePanel()), zset(new ZSetValuePanel()), hash(new HashValuePanel()), stream(new NoneValuePanel()),
        unknown(new UnknownValuePanel());

        private ValuePanel valuePanel;

        public static ValueType parseOf(String type) {
            try {
                return ValueType.valueOf(type);
            } catch (Exception e) {
                return unknown;
            }
        }
    }
}
